package cn.hejiang.order.service.impl;

import cn.hejiang.basic.service.impl.BaseServiceImpl;
import cn.hejiang.basic.util.CodeGenerateUtils;
import cn.hejiang.basic.util.PageList;
import cn.hejiang.order.constants.OrderConstants;
import cn.hejiang.order.domain.AdoptOrder;
import cn.hejiang.order.domain.OrderAddress;
import cn.hejiang.order.mapper.AdoptOrderMapper;
import cn.hejiang.order.mapper.OrderAddressMapper;
import cn.hejiang.order.query.AdoptOrderQuery;
import cn.hejiang.order.service.IAdoptOrderService;
import cn.hejiang.org.domain.Employee;
import cn.hejiang.org.mapper.EmployeeMapper;
import cn.hejiang.pay.constants.PayConstants;
import cn.hejiang.pay.domain.PayBill;
import cn.hejiang.pay.mapper.PayBillMapper;
import cn.hejiang.pay.service.IPayBillService;
import cn.hejiang.pet.domain.Pet;
import cn.hejiang.pet.mapper.PetMapper;
import cn.hejiang.quartz.constans.JobTypes;
import cn.hejiang.quartz.service.IQuartzService;
import cn.hejiang.quartz.utils.QuartzJobInfo;
import cn.hejiang.user.domain.LoginInfo;
import cn.hejiang.user.domain.User;
import cn.hejiang.user.domain.UserAddress;
import cn.hejiang.user.mapper.UserAddressMapper;
import cn.hejiang.user.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdoptOrderServiceImpl extends BaseServiceImpl<AdoptOrder> implements IAdoptOrderService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private AdoptOrderMapper adoptOrderMapper;

    @Autowired
    private OrderAddressMapper orderAddressMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private UserAddressMapper userAddressMapper;

    @Autowired
    private PayBillMapper payBillMapper;

    @Autowired
    private IPayBillService payBillService;

    @Autowired
    private IQuartzService quartzService;

    @Override
    @Transactional
    public String submit(Map<String, Object> params, LoginInfo loginInfo) {
        // 校验参数
        // 送货方式
        Integer serviceMethod = Integer.valueOf(params.get("service_method").toString());
        // 收货地址
        Long addressId = Long.valueOf(params.get("address_id").toString()) ;
        // 支付方式 1 支付宝 2 微信 0银联
        Long payMethod =  Long.valueOf(params.get("pay_method").toString());
        Long petId = Long.valueOf(params.get("pet_id").toString());
        // 修改宠物状态 + 下架时间 + 绑定领养人
        Pet pet = petMapper.loadById(petId);
        User user = userMapper.loadByLoginInfoId(loginInfo.getId());
        pet.setUser_id(user.getId());
        pet.setOffsaletime(new Date());
        pet.setState(0);
        petMapper.update(pet);
        // 创建领养订单
        // 订单本表
        AdoptOrder order = initAdoptOrder(pet, user);
        // 为了生成订单不用再来修改订单，直接生成统一支付标识
        order.setPaySn(CodeGenerateUtils.generateUnionPaySn());
        // 返回自增ID
        adoptOrderMapper.save(order);
        // 订单地址表
        UserAddress userAddress = userAddressMapper.loadById(addressId);
        OrderAddress orderAddress = initOrderAddress(order, userAddress);
        orderAddressMapper.save(orderAddress);
        // 支付订单并支付
        PayBill bill = initPayBill(payMethod, user, order);
        payBillMapper.save(bill);

        // 超时未支付自动取消
        QuartzJobInfo jobInfo = new QuartzJobInfo();
        jobInfo.setJobName(JobTypes.PAY_OVER_TIME_ADOPT_ORDER + order.getId());
        HashMap<String, Object> map = new HashMap<>();
        map.put("type", JobTypes.PAY_OVER_TIME_ADOPT_ORDER);
        map.put("orderId", order.getId());
        jobInfo.setParams(map);
        // 超时自动取消
        jobInfo.setFireDate(order.getLastPayTime());
        quartzService.addJob(jobInfo);

        // 封装的统一支付接口  返回支付接口的响应数据包
        return payBillService.pay(bill);
    }

    private PayBill initPayBill(Long payMethod, User user, AdoptOrder order) {
        PayBill bill = new PayBill();
        bill.setDigest(order.getDigest());
        bill.setMoney(order.getPrice());
        bill.setUnionPaySn(order.getPaySn());// 直接拿
        bill.setLastPayTime(new Date(System.currentTimeMillis() + OrderConstants.LAST_PAY_TIME));
        bill.setPayChannel(payMethod);
        bill.setBusinessType(PayConstants.BUSINESS_TYPE_ADOPT);// 领养订单类型
        bill.setBusinessKey(order.getId());
        bill.setUser_id(order.getUser_id());
        bill.setShop_id(order.getShop_id());
        bill.setNickName(user.getUsername());
        return bill;
    }

    private OrderAddress initOrderAddress(AdoptOrder order, UserAddress userAddress) {
        OrderAddress orderAddress = new OrderAddress();
        BeanUtils.copyProperties(userAddress, orderAddress);
        orderAddress.setOrder_id(order.getId());
        orderAddress.setOrderSn(order.getOrderSn());
        return orderAddress;
    }

    private AdoptOrder initAdoptOrder(Pet pet, User user) {
        AdoptOrder order = new AdoptOrder();
        order.setDigest("[摘要]对"+pet.getName()+"领养订单！");
        order.setPrice(pet.getSaleprice());
        String orderSn = CodeGenerateUtils.generateOrderSn(user.getId());
        order.setOrderSn(orderSn);
        order.setPet_id(pet.getId());
        order.setUser_id(user.getId());
        order.setShop_id(pet.getShop_id());
        order.setLastPayTime(new Date(System.currentTimeMillis() + OrderConstants.LAST_PAY_TIME));// 支付超时自动取消
        return order;
    }

    @Override
    public PageList<AdoptOrder> admin(AdoptOrderQuery query, LoginInfo loginInfo) {
        Employee employee = employeeMapper.loadByLoginInfoId(loginInfo.getId());
        if (employee != null) {
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    @Override
    public PageList<AdoptOrder> user(AdoptOrderQuery query, LoginInfo loginInfo) {
        User user = userMapper.loadByLoginInfoId(loginInfo.getId());
        query.setUserId(user.getId());
        return super.queryPage(query);
    }

    @Override
    public void deleteByQuartz(Long orderId) {
        AdoptOrder adoptOrder = adoptOrderMapper.loadById(orderId);
        if (adoptOrder.getState() == 0) {
            adoptOrder.setState(-1);
            adoptOrderMapper.update(adoptOrder);
            System.out.println("触发定时任务取消订单" + orderId);
        }
    }
}


